<script setup>
import { nextTick, ref, useTemplateRef } from 'vue';
import ChatList from './chatList.vue';
import IATRecorder from "@u/iat/iatRecorder.js";
import TTSRecorder from "@u/tts/ttsRecorder.js"
let iatRecorder = null; // 语音转文本
let ttsrecorder = null; // 文本转语音

const chatMsg = useTemplateRef('chatMsg');
const chatList = ref([]);

const addChatItem = (item) => {
  let itemObj = {
    role: item.role,
    content: item.content,
    time: new Date().toLocaleTimeString()
  }
  if(item.role === 'user'){
    chatList.value.push(itemObj);
  }else{
    chatList.value.push(itemObj);
  }
}



const initIatRecorder = () => { 
  iatRecorder = new IATRecorder(); // 听写
  iatRecorder.onWillStatusChange = async (oldStatus, status) => {
    console.log(status);    
  }
  iatRecorder.onTextChange = async (txt) => {
    if (iatRecorder.status === "end"){
        console.log('语音返回测试1',txt)
    }else {
      if(txt){
        console.log('语音返回测试2',txt)
      }
    }
  }
}

const initTtsRecorder = () => {
  ttsrecorder = new TTSRecorder(); // 合成
  ttsrecorder.onWillStatusChange = function (oldStatus, status) {
    console.log(oldStatus,status);
  };
}


const initAudio = () =>{
  return new Promise((resolve, reject) => {
    const audio = new Audio('/public/wx.mp3');
    resolve(audio);
  })
}


const stopRecording = () => {
  iatRecorder.stop();
}
const startRecording = () => {
  console.log('开始录音');
  console.log(iatRecorder.status);
  iatRecorder.start();
}
const scrollToBottom = () => {
  if(chatMsg.value){
    nextTick(() => {
      chatMsg.value.scrollTop = chatMsg.value.scrollHeight;
    })
  }
}


onMounted(async () => {
//  const audio =  await initAudio();
//   let playCount = 0;
  // const playAudio = () => {
  //   if (playCount < 3) {
  //     audio.play();
  //     playCount++;
  //   }
  // };
  // audio.addEventListener('ended', playAudio);
  // playAudio();
  // initIatRecorder()
  initTtsRecorder()
  // iatRecorder.start();
  scrollToBottom()
})
</script>
  
<template>
  <div class="chat" >
    <div class="chat_msg" ref="chatMsg" >
      <ChatList :chatList="chatList" />
    </div>
  </div>
</template> 

<style lang="scss" scoped>
.chat{
  width: 100vw;
  height: 100vh;
  background-color: pink;
  display: flex;  
  .chat_msg{
    width: 460px;
    background-color: #f9f9f9;
    overflow-y: scroll;
    // 平滑滚动
    scroll-behavior: smooth;
    &::-webkit-scrollbar {
      width: 3px; /* 设置滚动条宽度 */
    }
    &::-webkit-scrollbar-thumb {
      background-color: #E3EFFF; /* 设置滚动条颜色 */
      border-radius: 5px; /* 设置滚动条边框半径 */
    }

    &::-webkit-scrollbar-track {
      background-color: #fff; /* 设置滚动条轨道颜色 */
    }

    &::-webkit-scrollbar-track-piece {
      background-color: #fff; /* 设置滚动条轨道颜色 */
    }


  }
}
</style>